extends PanelContainer

signal unit_purchased(unit_data)

@onready var shop_container = $VBoxContainer/ShopGrid
@onready var gold_label = $VBoxContainer/Header/GoldLabel
@onready var refresh_button = $VBoxContainer/Header/RefreshButton
@onready var round_manager = get_node("/root/Main/RoundManager")

@export var shop_size: int = 5
@export var refresh_cost: int = 2

var current_shop_units: Array[UnitData] = []
var available_units: Array[UnitData] = []
var selected_button = null  # Track the currently selected button
var economy_manager  # Don't use @onready, we'll find it manually

func _ready():
	# Find EconomyManager with multiple fallback methods
	economy_manager = get_node_or_null("/root/Main/EconomyManager")
	if not economy_manager:
		economy_manager = get_node_or_null("../../EconomyManager")  # Try relative path
	if not economy_manager:
		# Try to find it in the scene tree
		var main_node = get_node_or_null("/root/Main")
		if main_node:
			economy_manager = main_node.get_node_or_null("EconomyManager")
	
	# Connect to economy manager for gold tracking
	if economy_manager:
		economy_manager.gold_changed.connect(_on_gold_changed)
		print("ShopUI connected to EconomyManager")
		print("Current gold: ", economy_manager.current_gold)
	else:
		print("WARNING: ShopUI couldn't find EconomyManager!")
		print("Using fallback gold system with 10 starting gold")
		set_meta("fallback_gold", 10)
		_on_gold_changed(10)
	
	setup_shop()
	create_default_units()
	refresh_shop()
	
	# Update gold display from economy manager or fallback
	if economy_manager:
		_on_gold_changed(economy_manager.current_gold)
	else:
		_on_gold_changed(get_meta("fallback_gold", 10))
	
	if refresh_button:
		refresh_button.pressed.connect(_on_refresh_pressed)
	
	if round_manager:
		round_manager.round_started.connect(_on_round_started)

func setup_shop():
	custom_minimum_size = Vector2(400, 200)
	
	if not shop_container:
		var vbox = VBoxContainer.new()
		vbox.name = "VBoxContainer"
		add_child(vbox)
		
		var header = HBoxContainer.new()
		header.name = "Header"
		vbox.add_child(header)
		
		gold_label = Label.new()
		gold_label.name = "GoldLabel"
		gold_label.text = "Gold: 10"
		gold_label.add_theme_font_size_override("font_size", 18)
		header.add_child(gold_label)
		
		header.add_spacer(false)
		
		refresh_button = Button.new()
		refresh_button.name = "RefreshButton"
		refresh_button.text = "Refresh (2g)"
		header.add_child(refresh_button)
		
		shop_container = HBoxContainer.new()
		shop_container.name = "ShopGrid"
		shop_container.add_theme_constant_override("separation", 10)
		vbox.add_child(shop_container)

func create_default_units():
	var tank_data = UnitData.new()
	tank_data.unit_name = "Tank"
	tank_data.tier = 1
	tank_data.cost = 2
	tank_data.max_health = 200
	tank_data.attack_damage = 15
	tank_data.attack_speed = 0.8
	tank_data.movement_speed = 4
	tank_data.attack_range = 2
	tank_data.unit_class = "Tank"
	tank_data.model_color = Color(0.3, 0.3, 0.8)
	available_units.append(tank_data)
	
	var fighter_data = UnitData.new()
	fighter_data.unit_name = "Fighter"
	fighter_data.tier = 1
	fighter_data.cost = 1
	fighter_data.max_health = 100
	fighter_data.attack_damage = 20
	fighter_data.attack_speed = 1.0
	fighter_data.movement_speed = 5
	fighter_data.attack_range = 2.5
	fighter_data.unit_class = "Fighter"
	fighter_data.model_color = Color(0.8, 0.3, 0.3)
	available_units.append(fighter_data)
	
	var archer_data = UnitData.new()
	archer_data.unit_name = "Archer"
	archer_data.tier = 1
	archer_data.cost = 2
	archer_data.max_health = 80
	archer_data.attack_damage = 25
	archer_data.attack_speed = 1.2
	archer_data.movement_speed = 4.5
	archer_data.attack_range = 5
	archer_data.unit_class = "Ranged"
	archer_data.model_color = Color(0.3, 0.8, 0.3)
	available_units.append(archer_data)
	
	var mage_data = UnitData.new()
	mage_data.unit_name = "Mage"
	mage_data.tier = 2
	mage_data.cost = 3
	mage_data.max_health = 70
	mage_data.attack_damage = 35
	mage_data.attack_speed = 0.9
	mage_data.movement_speed = 4
	mage_data.attack_range = 4
	mage_data.unit_class = "Mage"
	mage_data.model_color = Color(0.8, 0.3, 0.8)
	available_units.append(mage_data)
	
	var assassin_data = UnitData.new()
	assassin_data.unit_name = "Assassin"
	assassin_data.tier = 2
	assassin_data.cost = 3
	assassin_data.max_health = 90
	assassin_data.attack_damage = 40
	assassin_data.attack_speed = 1.5
	assassin_data.movement_speed = 6
	assassin_data.attack_range = 2
	assassin_data.unit_class = "Assassin"
	assassin_data.model_color = Color(0.5, 0.2, 0.7)
	available_units.append(assassin_data)

func refresh_shop():
	clear_shop()
	current_shop_units.clear()
	
	for i in range(shop_size):
		var random_unit = available_units.pick_random()
		current_shop_units.append(random_unit)
		create_shop_button(random_unit, i)

func clear_shop():
	for child in shop_container.get_children():
		child.queue_free()

func create_shop_button(unit_data: UnitData, index: int):
	var button = Button.new()
	button.custom_minimum_size = Vector2(70, 90)
	button.tooltip_text = "HP: %d\nDMG: %d\nSPD: %.1f" % [unit_data.max_health, unit_data.attack_damage, unit_data.movement_speed]
	
	var vbox = VBoxContainer.new()
	vbox.mouse_filter = Control.MOUSE_FILTER_IGNORE
	button.add_child(vbox)
	
	var color_rect = ColorRect.new()
	color_rect.custom_minimum_size = Vector2(60, 50)
	color_rect.color = unit_data.model_color
	color_rect.mouse_filter = Control.MOUSE_FILTER_IGNORE
	vbox.add_child(color_rect)
	
	var name_label = Label.new()
	name_label.text = unit_data.unit_name
	name_label.add_theme_font_size_override("font_size", 12)
	name_label.mouse_filter = Control.MOUSE_FILTER_IGNORE
	vbox.add_child(name_label)
	
	var cost_label = Label.new()
	cost_label.text = str(unit_data.cost) + "g"
	cost_label.add_theme_font_size_override("font_size", 14)
	cost_label.add_theme_color_override("font_color", Color(1, 0.8, 0))
	cost_label.mouse_filter = Control.MOUSE_FILTER_IGNORE
	vbox.add_child(cost_label)
	
	button.pressed.connect(_on_unit_button_pressed.bind(unit_data, index))
	shop_container.add_child(button)

func _on_unit_button_pressed(unit_data: UnitData, index: int):
	# Fallback if no economy manager - use local gold tracking
	if not economy_manager:
		print("WARNING: No economy manager found - using fallback gold system")
		# Create a simple fallback gold value
		if not has_meta("fallback_gold"):
			set_meta("fallback_gold", 10)  # Starting gold
		
		var current_gold = get_meta("fallback_gold")
		if current_gold >= unit_data.cost:
			set_meta("fallback_gold", current_gold - unit_data.cost)
			_on_gold_changed(get_meta("fallback_gold"))
			emit_signal("unit_purchased", unit_data)
			
			# Visual feedback
			var button = shop_container.get_child(index)
			if button:
				button.disabled = true
				button.modulate = Color(0.5, 0.5, 0.5)
				button.tooltip_text = "Already purchased - Click on board to place"
			
			print("Purchased (fallback): ", unit_data.unit_name, " for ", unit_data.cost, " gold")
			print("Remaining gold (fallback): ", get_meta("fallback_gold"))
		else:
			print("Not enough gold (fallback)! Need ", unit_data.cost, " but have ", current_gold)
		return
		
	# Normal path with economy manager
	if economy_manager.current_gold >= unit_data.cost:
		# Spend the gold through economy manager
		if economy_manager.spend_gold(unit_data.cost):
			emit_signal("unit_purchased", unit_data)
			
			# Visual feedback - mark button as purchased
			var button = shop_container.get_child(index)
			if button:
				button.disabled = true
				button.modulate = Color(0.5, 0.5, 0.5)
				button.tooltip_text = "Already purchased - Click on board to place"
			
			# Clear any previous selection
			if selected_button and selected_button != button:
				selected_button.modulate = Color(1, 1, 1)
			selected_button = button
			
			print("Purchased: ", unit_data.unit_name, " for ", unit_data.cost, " gold")
			print("Remaining gold: ", economy_manager.current_gold)
			print("Click on the board to place this unit!")
		else:
			print("Failed to spend gold!")
	else:
		print("Not enough gold! Need ", unit_data.cost, " but have ", economy_manager.current_gold)

func _on_refresh_pressed():
	if not economy_manager:
		return
		
	if economy_manager.current_gold >= refresh_cost:
		if economy_manager.spend_gold(refresh_cost):
			refresh_shop()
			print("Shop refreshed for ", refresh_cost, " gold!")
	else:
		print("Not enough gold to refresh!")

func _on_gold_changed(new_amount: int):
	if gold_label:
		gold_label.text = "Gold: " + str(new_amount)

func update_gold_display():
	# This function is now handled by _on_gold_changed
	if economy_manager:
		_on_gold_changed(economy_manager.current_gold)

func _on_round_started(round_number: int):
	# Add round income through economy manager
	if economy_manager:
		var income = economy_manager.calculate_round_income(true)  # Assuming win for now
		economy_manager.add_gold(income)
		print("Round ", round_number, " started - Income: ", income, " gold")
	refresh_shop()
